import { PropsWithChildren } from 'react'
import { useLaunch, getApp, getSetting, authorize, showModal, openSetting, showToast } from '@tarojs/taro'
import { installLogFilter } from './utils/logControl'
import { AuthProvider } from './contexts'

import './app.scss'

// 引入我们在 aienv 配置中提供的获取基地址方法
import { API_BASE_URL, getAvailableBaseURL } from '../config/env'

function App({ children }: PropsWithChildren<any>) {
  // 按需调用的录音权限函数，供页面触发
  const requestRecordPermission = async (): Promise<boolean> => {
    try {
      const authSetting = await getSetting()

      if (authSetting.authSetting['scope.record'] === false) {
        const res = await showModal({
          title: '需要录音权限',
          content: '为了提供语音输入功能，需要获取录音权限，请在设置中开启',
          confirmText: '去设置',
          cancelText: '取消'
        })
        if (res.confirm) {
          await openSetting()
          const after = await getSetting()
          const granted = !!after.authSetting['scope.record']
          const app = getApp<{ globalData: any }>()
          if (!app.globalData) app.globalData = {}
          app.globalData.hasRecordPermission = granted
          return granted
        }
        return false
      } else if (authSetting.authSetting['scope.record'] === undefined) {
        await authorize({ scope: 'scope.record' })
        const app = getApp<{ globalData: any }>()
        if (!app.globalData) app.globalData = {}
        app.globalData.hasRecordPermission = true
        return true
      } else {
        const app = getApp<{ globalData: any }>()
        if (!app.globalData) app.globalData = {}
        app.globalData.hasRecordPermission = true
        return true
      }
    } catch (error) {
      console.error('录音权限请求失败:', error)
      showToast({ title: '录音权限获取失败', icon: 'none', duration: 2000 })
      return false
    }
  }

  useLaunch(async () => {
    console.log('App launched.')
    
    // 设置全局 api 基地址，供各页面使用
    const app = getApp<{ globalData: any }>()
    if (!app.globalData) app.globalData = {}
    
    // 异步获取可用的API地址
    try {
      console.log('🔍 正在检测可用的API地址...')
      const availableApiBase = await getAvailableBaseURL()
      app.globalData.apiBase = availableApiBase
      
      try {
        // 同步写入，方便页面通过 Storage 读取
        // @ts-ignore
        wx.setStorageSync('API_BASE', availableApiBase)
      } catch (_) {}
      console.log('✅ API_BASE 设置为:', availableApiBase)
    } catch (error) {
      console.error('❌ 获取可用API地址失败，使用默认地址:', error)
      app.globalData.apiBase = API_BASE_URL
      try {
        // @ts-ignore
        wx.setStorageSync('API_BASE', API_BASE_URL)
      } catch (_) {}
      console.log('⚠️ 使用默认API_BASE:', API_BASE_URL)
    }

    // 将按需调用的方法暴露到全局
    app.globalData.requestRecordPermission = requestRecordPermission

    // 启动时同步当前权限状态
    getSetting().then(s => {
      app.globalData.hasRecordPermission = !!s.authSetting['scope.record']
    }).catch(() => {})
    
    installLogFilter()
  })

  // children 是将要会渲染的页面
  return (
    <AuthProvider>
      {children}
    </AuthProvider>
  )
}

export default App
